package com.example.ribbonserver.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2020/4/22
 */
@Service
public class HelloService {

    private static final Logger logger = LoggerFactory.getLogger(HelloService.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 默认线程名称 （HelloService-数字）--->  groupKey ---> ThreadPoolKey
     * @param name
     * @return
     */
    @HystrixCommand(fallbackMethod = "fallbackMethod", groupKey = "myGroupKey", threadPoolKey = "myThreadPoolKey")
    public String get(String name) {
        logger.info("------------get" + name);
        return restTemplate.getForObject("http://EUREKA-CLIENT/hello?name=" + name, String.class);
    }

    public String fallbackMethod(String name, Throwable throwable) {
        logger.info("-------------------" + name);
        logger.info("-----------"+ throwable.getMessage());
        return "circuit hystrix";
    }

    @HystrixCommand(observableExecutionMode = ObservableExecutionMode.EAGER, ignoreExceptions = {NullPointerException.class})
    public Future<String> getAsyn(String name) {
        return new AsyncResult<String>() {
            @Override
            public String invoke() {
                return restTemplate.getForObject("http://EUREKA-CLIENT/hello?name=" + name, String.class);
            }
        };
    }
}
